package com.example.jpa.demo_jpa.listener;

import com.example.jpa.demo_jpa.model.AyUser;
import com.example.jpa.demo_jpa.model.Visit;
import com.example.jpa.demo_jpa.service.AyUserService;
import com.example.jpa.demo_jpa.service.VisitService;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

@WebListener
public class RequestListener implements ServletRequestListener {
    @Resource
    VisitService visitService;
    @Resource
    private AyUserService ayUserService;
    private static final String ALL_USER = "ALL_USER_LIST";
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("---------------------------->请求Listener销毁");
    }
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("---------------------------->请求Listener创建");
//        Visit visit = visitService.findById("1");
//        visit.setTimes(visit.getTimes() + 1);
//        visitService.save(visit);

        //查询数据库所有的用户
        List<AyUser> ayUsers = ayUserService.findAll();
        //清除redis中的缓存数据
        redisTemplate.delete(ALL_USER);
        //将visit数据存到Redis缓存中
        redisTemplate.opsForList().leftPushAll(ALL_USER, ayUsers);
        //真实项目中需要注释掉
        List<AyUser> queryAyUserList = redisTemplate.opsForList().range(ALL_USER,0,-1);
        System.out.println("缓存中的访问次数为：" + queryAyUserList.size() + "人！！！");

    }
}